<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { AxiosError } from 'axios';
import {
  getJobListData,
  updateJobStatus,
  getCandidate,
  updateCandidate,
} from '../services/job';
import { JobListApiResult } from '../services/model/JobModel';
import { JobListItem, JOB_STATUS } from '../types/Job';
import CandidateList from '../components/CandidateListComponent.vue';
import { Candidate } from '../types/Candidate';
// 职位列表数据
const listData = ref<JobListApiResult>();
// 加载标示符
const loading = ref<boolean>(false);
// 获取表格数据
const getData = async (page: number) => {
  loading.value = true;
  try {
    const response = await getJobListData(page);
    loading.value = false;
    if (response.status === 200) {
      listData.value = response.data;
    }
  } catch (error) {
    loading.value = false;
    if ((error as AxiosError).name !== 'CanceledError') {
      ElMessage.error('请求数据发生错误');
    }
  }
};
// 第一次进入页面，请求第1页数据
onMounted(() => {
  getData(1);
});
// 分页跳转函数，跳转到val页数据
const handlePageChange = (val: number) => {
  getData(val);
};
// 当前职位下线操作
const handleDelete = (index: number, data: JobListItem) => {
  // 二次确认删除
  ElMessageBox.confirm(`确定要把“${data.title}”职位招聘下线么?`, '警告', {
    confirmButtonText: '下线',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(async () => {
      const response = await updateJobStatus(data.id, JOB_STATUS.DELETED);
      if (response.status === 201) {
        ElMessage.success('删除成功');
        if (listData.value) {
          listData.value.data_list[index].status = JOB_STATUS.DELETED;
        }
      } else {
        ElMessage.error('删除发生错误');
      }
    })
    .catch((error) => {
      if ((error as AxiosError).name !== 'CanceledError') {
        ElMessage.error('发生错误');
      }
    });
};
// 面试者管理弹窗
const interviewVisible = ref(false);
// 面试者管理请求加载标识符
const interviewLoading = ref(false);
// 面试者列表数据
const interviewData = ref<Candidate[]>();
// 打开面试者管理列表弹窗
const handleInterview = async (index: number, row: JobListItem) => {
  interviewVisible.value = true;
  interviewLoading.value = true;
  interviewData.value = undefined;
  try {
    const response = await getCandidate(row.id);
    if (response.status === 200) {
      interviewLoading.value = false;
      interviewData.value = response.data.data_list;
    }
  } catch (error) {
    interviewLoading.value = false;
    if ((error as AxiosError).name !== 'CanceledError') {
      ElMessage.error('请求失败');
    }
  }
};
// 状态栏tag颜色显示
const statusType = (status: string): string => {
  if (status === JOB_STATUS.PUBLISHED) {
    return '';
  }
  if (status === JOB_STATUS.FINISHED) {
    return 'success';
  }
  return 'danger';
};

// 操作按钮是否可以点击
const disableButton = (data: JobListItem): boolean => {
  return data.status === JOB_STATUS.DELETED;
};
// 分页总数
const paginationTotal = computed(() => {
  return listData.value?.total ? listData.value?.total : 0;
});
// 分页当前页数
const paginationCur = computed(() => {
  return listData.value?.cur ? listData.value?.cur : 0;
});
// 更新面试者信息
const handleUpdateCandidate = async (
  data: Candidate,
  index: number,
  callback: (index: number) => void
) => {
  try {
    const response = await updateCandidate(data);
    if (response.status === 200) {
      ElMessage.success('提交成功');
      callback(index);
    }
  } catch (error) {
    if ((error as AxiosError).name !== 'CanceledError') {
      ElMessage.error('提交失败');
    }
  }
};
</script>

<template>
  <div>
    <div class="container">
      <el-table
        v-loading="loading"
        :data="listData?.data_list"
        border
        class="table"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column prop="title" label="职位标题">
          <template #default="scope">
            <el-link type="primary" :href="scope.row.job_url" target="_blank">{{
              scope.row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="publish_time"
          label="发布时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="visit_num"
          width="90"
          label="浏览次数"
        ></el-table-column>
        <el-table-column
          prop="resume_num"
          width="90"
          label="收到申请"
        ></el-table-column>
        <el-table-column prop="publish_time" width="90" label="招聘进度">
          <template #default="scope"
            >{{ scope.row.current }} / {{ scope.row.target }}</template
          >
        </el-table-column>
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="statusType(scope.row.status)">{{
              scope.row.status
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="publisher_name"
          width="90"
          label="发布者"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              size="small"
              icon="eli-document"
              type="warning"
              plain
              :disabled="disableButton(scope.row)"
              @click="handleInterview(scope.$index, scope.row)"
              >面试管理</el-button
            >
            <el-button
              size="small"
              type="danger"
              icon="eli-delete"
              plain
              :disabled="disableButton(scope.row)"
              @click="handleDelete(scope.$index, scope.row)"
              >下线</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="paginationCur"
          :total="paginationTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 面试者管理弹出框 -->
    <el-dialog v-model="interviewVisible" title="管理面试" width="80%">
      <CandidateList
        :loading="interviewLoading"
        :data="interviewData"
        @submit="handleUpdateCandidate"
      ></CandidateList>
    </el-dialog>
  </div>
</template>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
